package com.pxmeta.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.comment.entity.CommentUserLike;
import com.pxmeta.comment.entity.dto.CommentLikeDTO;
import com.pxmeta.comment.mapper.CommentUserLikeMapper;
import com.pxmeta.comment.service.ICommentUserLikeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户评论点赞表 服务实现类
 * </p>
 *
 * @author wcl
 * @since 2022-06-28
 */
@Service
public class CommentUserLikeServiceImpl extends ServiceImpl<CommentUserLikeMapper, CommentUserLike> implements ICommentUserLikeService {

    @Override
    @Transactional
    public void like(CommentLikeDTO dto, Long userId) {
        Long commentId = dto.getCommentId();
        boolean isLike = isLike(userId, commentId);
        //如果已经喜欢，则取消喜欢
        if (isLike){
            dislike(userId, commentId);
        }else {
            CommentUserLike like = new CommentUserLike();
            like.setCommentId(commentId);
            like.setUserId(userId);
            this.save(like);
        }
    }


    /**
     * 查询是否喜欢
     * @return
     */
    public boolean isLike(Long userId, Long commentId){
        LambdaQueryWrapper<CommentUserLike> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommentUserLike::getUserId, userId)
                .eq(CommentUserLike::getCommentId, commentId);
        CommentUserLike like = this.getOne(wrapper);
        return like != null;
    }


    public void dislike(Long userId, Long commentId){
        LambdaQueryWrapper<CommentUserLike> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommentUserLike::getUserId, userId)
                .eq(CommentUserLike::getCommentId, commentId);
        CommentUserLike like = this.getOne(wrapper);
        this.removeById(like);
    }
}
